﻿@{
    ViewBag.Title = "Home Page";
    Layout = null;
}


<div class="mytool">

    <input type="text" id="txtSearch" placeholder="线路名称" />
    <input type="button" value="查询" id="btnSearch">
    <BR>
    <BR>
    <input type="button" id="btnShowAlarm" value="故障定位" /><BR><BR>
    <div id="alarm_panel" style="display:none;">
        <select id="alarm_line">
            <option value="-1">请选择故障路线</option>
        </select><br /><BR>
        <select id="alarm_point">
            <option value="-1">请选择检测端点</option>
        </select><br /><BR>
        <input type="text" id="alarm_lan" placeholder="故障距离，单位:米" />
        <br /><BR>
        <input type="button" id="btnAlarm" value="开始定位" />
    </div>

    <BR>
    <div style="width:100%; height:auto; margin-bottom:10px;">
        线路指示
        <ul id="linePanel"></ul>
        <br />
        @*经度:<input type="text" id="txtKm" value="114.517925"><br>
            纬度:<input type="text" id="lat" value="36.618941"><br>
            <input type="button" value="发出警报" id="btnAlarm" /><br>
            <input type="button" value="删除警报" id="btnDelAlarm">*@
    </div>

</div>
<div id="allmap" style="border-left:1px solid #000"></div>

<script type="text/javascript">

    // 百度地图API功能
    var map = new BMap.Map("allmap");
    var alarmMaker = [];  //保存添加的警报点
    var myPoloyLine = []; //保存添加的折线

    map.setMapStyle({
        styleJson: [
          {
              "featureType": "label",
              "elementType": "all",
              "stylers": {
                  "visibility": "on"
              }
          },
         {
             "featureType": "poi",
             "elementType": "all",
             "stylers": {
                 "color": "#ffffff"
             }
         },
         {
             "featureType": "background",
             "elementType": "all",
             "stylers": {
                 "color": "#ffffff"
             }
         },
         {
             "featureType": "highway",
             "elementType": "geometry.fill",
             "stylers": {
                 "visibility": "on"
             }
         },
         {
             "featureType": "highway",
             "elementType": "geometry.stroke",
             "stylers": {
                 "visibility": "on"
             }
         },
         {
             "featureType": "railway",
             "elementType": "all",
             "stylers": {
                 "visibility": "on"
             }
         },
         {
             "featureType": "local",
             "elementType": "all",
             "stylers": {
                 "visibility": "on"
             }
         },
         {
             "featureType": "arterial",
             "elementType": "all",
             "stylers": {
                 "visibility": "on"
             }
         },
         {
             "featureType": "boundary",
             "elementType": "geometry.fill",
             "stylers": {
                 "color": "#e06666",
                 "visibility": "on"
             }
         }
        ]
    });

    //map.setMapStyle({ style: 'googlelite' });
    map.centerAndZoom("邯郸", 11);
    //map.disableDragging();     //禁止拖拽
    map.enableDragging();   //开启拖拽
    map.enableScrollWheelZoom(true); // 启动缩放地图
    map.addControl(new BMap.MapTypeControl()); // 添加地图类型控件
    var top_left_control = new BMap.ScaleControl({ anchor: BMAP_ANCHOR_TOP_LEFT });// 左上角，添加比例尺
    var top_left_navigation = new BMap.NavigationControl();  //左上角，添加默认缩放平移控件
    //var overViewOpen = new BMap.OverviewMapControl({ isOpen: true, anchor: BMAP_ANCHOR_BOTTOM_RIGHT });
    // 覆盖区域图层测试
    map.addTileLayer(new BMap.PanoramaCoverageLayer());
    var stCtrl = new BMap.PanoramaControl(); //构造全景控件
    stCtrl.setOffset(new BMap.Size(20, 40));
    map.addControl(stCtrl);//添加全景控件

    var ctrl = new BMapLib.TrafficControl({
        showPanel: false //是否显示路况提示面板
    });
    ctrl.setOffset(new BMap.Size(150, 10));
    map.addControl(ctrl);
    //ctrl.setAnchor(BMAP_ANCHOR_BOTTOM_LEFT);

    map.addControl(top_left_control);
    map.addControl(top_left_navigation);
    //map.addControl(overViewOpen);

    // 定义一个控件类,即function
    function ZoomControl() {
        // 默认停靠位置和偏移量
        this.defaultAnchor = BMAP_ANCHOR_BOTTOM_LEFT;
        this.defaultOffset = new BMap.Size(5, 35);
    }

    // 通过JavaScript的prototype属性继承于BMap.Control
    ZoomControl.prototype = new BMap.Control();

    // 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
    // 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
    ZoomControl.prototype.initialize = function (map) {
        // 创建一个DOM元素
        var div = document.createElement("div");
        // 添加文字说明
        div.appendChild(document.createTextNode("返回邯郸"));
        // 设置样式
        div.style.cursor = "pointer";
        div.style.border = "1px solid gray";
        div.style.color = "red";
        div.style.fontSize = 13;
        div.style.backgroundColor = "#fff";
        // 绑定事件,点击一次放大两级
        div.onclick = function (e) {
            map.centerAndZoom("邯郸", 11);
        }
        // 添加DOM元素到地图中
        map.getContainer().appendChild(div);
        // 将DOM元素返回
        return div;
    }
    // 创建控件
    var myZoomCtrl = new ZoomControl();
    // 添加到地图当中
    map.addControl(myZoomCtrl);

    var currentPosition = null;
    map.addEventListener("mousemove", function (e) {
        var jing_du_value = e.point.lng;
        var wei_du_value = e.point.lat;
        currentPosition = new BMap.Point(e.point.lng, e.point.lat);
    });

    var opts = {
        width: 250,     // 信息窗口宽度
        height: 110,     // 信息窗口高度
        title: "提示信息", // 信息窗口标题
        enableMessage: true //设置允许信息窗发送短息
    }

    //循环画出轮廓线
    for (var i = 0; i < data.boundary.length; i++) {
        getBoundary(data.boundary[i]);
    }
    showLinePanel();
    function drawLine() {
        $.post('/Data/GetLines', { name: $("#txtSearch").val() }, function (data) {
            if (!data)
                return;

            for (var i = 0; i < data.length; i++) {

                var linePoints = [];
                for (var item in data[i].Point) {
                    var p = new BMap.Point(data[i].Point[item].Lng, data[i].Point[item].Lat);
                    linePoints.push(p)
                }
                //定义折线
                var polyline = new BMap.Polyline(linePoints,
                    {
                        //strokeStyle: "dashed",
                        strokeColor: "#" + data[i].Color,
                        strokeWeight: 2,
                        strokeOpacity: 0.5
                    });
                map.addOverlay(polyline);     //添加折线到地图上
                myPoloyLine.push(polyline);
                polyline.addEventListener("mouseover", function (e) {

                    e.target.setStrokeOpacity(1);
                    e.target.setStrokeWeight(5)
                    //e.target.setStrokeColor("blue")

                });

                polyline.addEventListener("mouseout", function (e) {
                    e.target.setStrokeOpacity(0.5)
                    e.target.setStrokeWeight(2)
                    //e.target.setStrokeColor("#2828ff")
                });

                var d = data[i];
                polyline.addEventListener('click', function (e) {
                    var label = new BMap.Label("", opts);  // 创建文本标注对象
                    label.setStyle({
                        //color: "#fff",
                        backgroundColor: "blue",
                        //fontSize: "12px",
                        //lineHeight: "auto",
                        border: "1px solid blue",
                        width: "10px",
                        height: "10px",
                        padding: "0px",
                        //fontFamily: "微软雅黑"
                    });
                    var p = e.currentTarget;
                    var km = (e.currentTarget.LS / 1000).toFixed(2);
                    var html = '<div style="margin:0;line-height:20px;padding:2px;font-size:12px">' +
                           '线路名称:' + d.Name + '<br/>' +
                           '两地距离：' + km + '千米<br/>' +
                         '</div>'
                    var infoWindow = new BMap.InfoWindow(html, label);  // 创建信息窗口对象
                    map.openInfoWindow(infoWindow, currentPosition); //开启信息窗口

                })
            }
        })


    }
    drawLabel();
    function drawLabel() {

        $.post('/Data/GetAllPoints', {}, function (data) {
            if (!data)
                return;

            for (var i = 0; i < data.length; i++) {

                var point = new BMap.Point(data[i].Lng, data[i].Lat);
                var opts = {
                    position: point,    // 指定文本标注所在的地理位置
                    //offset   : new BMap.Size(0, 0)    //设置文本偏移量
                };

                if (data[i].PointType == "BDZ") {
                    var label = new BMap.Label(data[i].Name, opts);  // 创建文本标注对象
                    label.setStyle({
                        color: "#fff",
                        backgroundColor: "red",
                        fontSize: "12px",
                        padding: "0px",
                        fontFamily: "微软雅黑"
                    });

                    map.addOverlay(label);
                    addClickHandler(data[i], label);
                } else {
                    var label = new BMap.Label("", opts);  // 创建文本标注对象
                    label.setStyle({
                        backgroundColor: "blue",
                        border: "1px solid blue",
                        width: "10px",
                        height: "10px",
                        padding: "0px",
                    });

                    map.addOverlay(label);
                    addClickHandler(data[i], label);
                }
            }

        })


    }
    function addClickHandler(p, marker) {
        marker.addEventListener("click", function (e) {
            openInfo(p, e)
        }
		);
    }
    function openInfo(pt, e) {
        var p = e.target;
        var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);

        var gc = new BMap.Geocoder();
        var address = "未知地址";
        gc.getLocation(point, function (rs) {
            address = rs.address;
            var name = "";
            if (pt.PointType == "BDZ") {
                name = "变电站名称:" + pt.Name;
            } else {
                name = "线杆编号:" + pt.Name;
            }
            var html = '<div style="margin:0;line-height:20px;padding:2px;font-size:12px">' +
                            name + '<br/>' +
                            '经纬度:' + p.getPosition().lng + ',' + p.getPosition().lat + '<br/>' +
                            '备注:' + pt.Remark + '<br/>' +
                            '地址：' + address + '<br/>' +
                          '</div>'
            var infoWindow = new BMap.InfoWindow(html, opts);  // 创建信息窗口对象
            map.openInfoWindow(infoWindow, point); //开启信息窗口
        })
    }

    //画出区域轮廓线
    function getBoundary(data) {
        var bdary = new BMap.Boundary();
        bdary.get(data.split("-")[0], function (rs) {
            var bounds;
            var maxNum = -1, maxPly;
            var count = rs.boundaries.length;
            for (var i = 0; i < count; i++) {
                var line = 0.5;
                if (data.split("-")[0] == "邯郸") {
                    line = 2
                }
                var ply = new BMap.Polygon(rs.boundaries[i], { strokeStyle: "solid", strokeWeight: line, strokeOpacity: 0, fillColor: "", setFillOpacity: 0, strokeColor: "red" });
                map.addOverlay(ply);
            }
        });
    }

    function showLinePanel() {
        $.post('/Data/GetLines', {}, function (data) {
            var dic = new Array();
            for (var i = 0; i < data.length; i++) {
                if (dic[data[i].Name]) {
                    continue;
                }
                dic[data[i].Name] = data[i].Name;
                var html = '<li style="list-style-type:none"><div style="float:left; margin-top:2px;background-color:#' + data[i].Color + '; height:10px; width:10px;margin-right:10px;" ></div>' + data[i].Name + '</li>';
                $("#linePanel").append(html)
            }

            //查询下拉路线信息
            $.post('/data/GetLinesName', {}, function (data) {
                if (data) {
                    var linename = [];
                    var dic = new Array();
                    for (var item in data) {
                        if (dic[data[item].Name]) {
                            continue;
                        }
                        dic[data[item].Name] = data[item].Name;
                        linename.push('<option value="' + data[item].Name + '">' + data[item].Name + '</option>');
                    }
                    $("#alarm_line").append(linename.join(''));

                } else {
                    alert('加载数据失败！');
                }
            })

        })
    }

    $(function () {

        $("#btnAlarm").click(function () {

            var v = parseFloat($("#alarm_lan").val());
            var line = $("#alarm_line").val();
            var point = $("#alarm_point").val();

            $.post('/data/GetDWlines', { linename: line, point: point }, function (data) {
                if (data) {
                    var flag = false;
                    var target = [];
                    for (var line in data) {

                        var begin = {};
                        var end = {};
                        var tempv = v;

                        var points = data[line].Value;
                        if (points.length == 1) {
                            flag = false;
                            continue;

                        }
                        for (var i = 0; i < points.length; i++) {
                            if (i >= (points.length - 1)) {
                                flag = false;
                                break;
                            }
                            begin.x = points[i].Lng;
                            begin.y = points[i].Lat;
                            end.x = points[i + 1].Lng;
                            end.y = points[i + 1].Lat;

                            var tempLength = getDistance({
                                x: begin.x,
                                y: begin.y
                            }, {
                                x: end.x,
                                y: end.y
                            })

                            if (tempLength < tempv) {
                                tempv = tempv - tempLength;
                            } else {
                                flag = true;
                                break;
                            }
                        }

                        //获取到 两点坐标 和 具体的 tempV值
                        var insert = true;
                        if (target.length > 0) {
                            for (var i = 0; i < target.length; i++) {
                                if (target[i].p.x == begin.x && target[i].p.y == begin.y
                                    && target[i].p1.x == end.x && target[i].p1.y == end.y) {
                                    insert = false;
                                }
                            }
                        }
                        if (insert && flag) {
                            target.push({
                                p: begin,
                                p1: end,
                                v: tempv
                            })
                        }
                    }
                    if (target && target.length > 0) {

                        // 删除原来的
                        if (alarmMaker.length > 0) {
                            for (var i = 0; i < alarmMaker.length; i++) {
                                map.removeOverlay(alarmMaker[i])
                            }
                        }
                        alarmMaker.length = 0;
                        for (var i = 0; i < target.length; i++) {
                            getpoint(target[i].p, target[i].p1, target[i].v);
                        }
                    } else {
                        alert("输入有误，无法定位!")
                    }
                }
            })
        });

        //显示定位信息
        $("#btnShowAlarm").click(function () {
            $("#alarm_panel").fadeToggle();
           

        })
        $("#alarm_line").change(function () {
            $("#alarm_point").html('<option value="-1">请选择检测端点</option>');
            var name = $(this).val();
            $.post('/data/GetPointByLineName', { name: name }, function (data) {

                if (data) {
                    var points = [];
                    for (var item in data) {
                        points.push('<option value="' + data[item].Key + '">' + data[item].Value + '</option>');
                    }
                    $("#alarm_point").append(points.join(''))
                }
            })
        })
        $("#btnSearch").click(function () {
            if (myPoloyLine.length > 0) {
                for (var i = 0; i < myPoloyLine.length; i++) {
                    map.removeOverlay(myPoloyLine[i])
                }
            }
            myPoloyLine.length = 0;
            drawLine();
        });
    })


    function getDistance(begin, end) {
        var pointA = new BMap.Point(begin.x, begin.y);
        var pointB = new BMap.Point(end.x, end.y);
        return map.getDistance(pointA, pointB);
    }


    function getpoint(p, p1, v) {

        var pointA = new BMap.Point(p.x, p.y);
        var pointB = new BMap.Point(p1.x, p1.y);
        var tan = map.getDistance(pointA, pointB);

        var px = p.x;
        var py = p.y;

        var p1x = p1.x;
        var p1x = p1.y;


        var x = (p1.x - p.x) / tan * v;
        var y = (p1.y - p.y) / tan * v;
        var cx = x + p.x;
        var cy = y + p.y;

        var pointC = new BMap.Point(cx, cy);  // 创建点坐标B--江北区
        var tan1 = map.getDistance(pointA, pointC);
        var point = new BMap.Point(cx, cy);



        var marker = new BMap.Marker(point);  // 创建标注
        map.addOverlay(marker);

        marker.addEventListener("click", function (e) {
            openAlarmInfo(e)
        })

        marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画

        var circle = new BMap.Circle(point, 500, { fillColor: "blue", strokeWeight: 1, fillOpacity: 0.3, strokeOpacity: 0.3 });
        map.addOverlay(circle);
        map.centerAndZoom(point, 17);

        alarmMaker.push(marker);
        alarmMaker.push(circle);
    }


    function openAlarmInfo(e) {
        var p = e.target;
        var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);

        var gc = new BMap.Geocoder();
        var address = "未知地址";
        gc.getLocation(point, function (rs) {
            address = rs.address;
           
            var html = '<div style="margin:0;line-height:20px;padding:2px;font-size:12px">' +
                            '故障点<br/>'+
                            '经纬度:' + p.getPosition().lng + ',' + p.getPosition().lat + '<br/>' +
                            '地址：' + address + '<br/>' +
                          '</div>'
            var infoWindow = new BMap.InfoWindow(html,   {
                position: point,   
            });
            map.openInfoWindow(infoWindow, point); //开启信息窗口
        })
    }

</script>
